<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
    }
  </style>
</head>
<body>
  <div></div>

  <script>
    const div = document.querySelector("div");

    // isDown表示当前是否在div的里面被按下
    let isDown = false;
    let offsetX;
    let offsetY;

    div.addEventListener("mousedown", (e) => {
      isDown = true;
      console.log(e.clientX); // 鼠标离窗口左边的距离
      console.log(div.offsetLeft); // div元素离左边的距离
      offsetX = e.clientX - div.offsetLeft; // 鼠标离元素左边的距离
      offsetY = e.clientY - div.offsetTop; // 鼠标离元素左边的距离
      // div.style.top = "200px"
    })
    div.addEventListener("mousemove", (e) => {
      if (isDown) {
        // ...
        // 要去改变div的top和left属性  div.style.top = "xxxpx"
        // e.clientX
        // e.clientY
        // div.offsetLeft
        // div.offsetTop

        div.style.left = e.clientX - offsetX + "px";
        div.style.top = e.clientY - offsetY + "px";
      }
    })
    div.addEventListener("mouseup", (e) => {
      isDown = false
    })
  </script>
</body>
</html>